<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/5/27
 * Time: 16:32
 */

namespace Home\Controller;


use Home\Logic\CommentLogic;
use Home\Logic\GoodsLogic;
use Home\Logic\UserLogic;
//use Common\Log;
use Home\Model\Page;
use Think\Controller;
use Think\Log;

class GoodsController extends BaseController
{
    /**
     * 跳转到商品详情界面
     */
    public function introduction(){

        $goodsLogic = new GoodsLogic();
        $goods_id = I("get.goods_id");
        $goodsData = M('Goods')->where("goods_id = $goods_id")->find();
        if(empty($goodsData) || ($goodsData['is_on_sale'] == 0)){
            $this->error('该商品已经下架',U('Index/index'));
        }
        if($goodsData['brand_id']){
            $brnad = M('brand')->where("id =".$goodsData['brand_id'])->find();
            $goodsData['brand_name'] = $brnad['name'];
        }
        $goodsData['goods_content'] = str_replace('src', 'class="lazy"  data-original', $goodsData['goods_content']);

        $goodsData['goods_content'] = html_entity_decode($goodsData['goods_content']);
        echo "&nbsp ";

        $imageData = M('GoodsImages')->where("goods_id = $goods_id")->select(); // 商品 图册
//            $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
//            $goods_attr_list = M('GoodsAttr')->where("goods_id = $goods_id")->select(); // 查询商品属性表
        $filter_spec = $goodsLogic->get_spec($goods_id);

        $sameGoods = $goodsLogic->getSameGoods($goodsData['cat_id'], $goodsData['goods_id']);

        $spec_goods_price  = M('spec_goods_price')->where("goods_id = $goods_id")->getField("key,price,store_count,key_name"); // 规格 对应 价格 库存表
        //评论信息
        $commentInfo = $goodsLogic->commentStatistics($goods_id);
        //判断当前用户是否收藏该商品

        $user = $this->getUser();
        $count = D('GoodsCollect')
            ->where(array('user_id'=>$user['user_id'],'goods_id'=>$goods_id))->count();

        if($user['user_type'] == 1)
            $agent_price = $goodsData['agent_price'];
        else
            $agent_price = 0;


        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id = $goods_id")->select(); // 查询商品属性表
        self::jsSDK();//分享
        $this->assign('user_type', $user['user_type']); //代理商标识
        $this->assign('agent_price', $agent_price); //代理商可优惠价格 真实价格为商品价格-优惠价格
        $this->assign('is_collect',$count ? true: false);
        $this->assign('sameGoods', $sameGoods);
        $this->assign('imageData', $imageData);
        $this->assign('goodsData', $goodsData);
        $this->assign('filter_spec', $filter_spec);
        $this->assign("commentInfo",$commentInfo);
        $this->assign('spec_goods_price', json_encode($spec_goods_price,true)); // 规格 对应 价格 库存表
        $this->assign('index', 1);
        $this->assign('attribute', $goods_attribute);
        $this->assign('attr_list', $goods_attr_list);
        $this->display('detail');
    }

    /**
     * ajax分页获取商品评论列表
     */
    public function commentList(){
        $pagesize = 5;
        $pagenumber = I('pagenum', '1');
        $goods_id = I('goods_id');
        $type = I('type');
        $commentLogic = new CommentLogic();
        $data = $commentLogic->getCommentList($goods_id,$type,$pagenumber,$pagesize);
        $this->assign('data', $data);
//        var_dump($data);
        $this->display('ajaxComment');

        //        $this->ajaxReturn($data);
    }

    /**
     * 跳转到搜索界面
     */
    public function search(){
        $search = I('search');
        $type = I('type','0');
        if($type == 1){//通过分类查找
            $this->assign('category_id',$search);
            $search = M('GoodsCategory')->where(array('id'=>$search))->getField('name');
        }
        $this->assign('type',$type);
        $this->assign('search',$search);
        $this->assign('page_str','home');
        $this->display();
    }

    /**
     * ajax获取商品列表 搜索商品
     */
    public function goodsList(){
//        $json = session('city');
//        if($json) {
//            $city = $json['city'] . '市';
//            $cityId = M('region')->where(array('name' => $city))->getField('parent_id');
//            $map['region_id'] = $cityId;
//        }
        $user = $this->getUser();
        $pagesize = 10;
        $pagenumber = I('pagenum', '');
        $search = I('search');
        $type = I('type','0');
        $map['is_on_sale'] = 1;
        $sort_type = I('sort_type', '0');
        if($type == 1){
            $map['cat_id'] = I('category_id');
        }else{
            $map['goods_name'] = array('like', '%' . $search . '%');
        }

        if($sort_type == 1){

            $order = 'sales_sum desc';

        }
        else if($sort_type == 2)
            $order = 'shop_price asc';

        else
            $order = 'goods_id desc';

        $startno = ($pagenumber - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $goodsList = D('Goods')->where($map)->order($order)->limit($limit)->select();
        if($user['user_type'] == 1){
            foreach ($goodsList as $key => $val){
                $goodsList[$key]['shop_price'] -= $val['agent_price'];
            }

        }

        $data['list'] = $goodsList;
        $count = D('Goods')->where($map)->count();
        $page = new Page($pagenumber, $count, $pagesize);
        Log::write('sql:'.D('Goods')->getLastSql());
        //分页数据
//        $page['cpage'] = $pagenum;//当前页面
//        $page['totalnum'] = floor(($count + $pagesize - 1) / $pagesize);
        $data['page'] = $page;
        $data['map'] = $map;
        $data['order'] = $order;
        $this->ajaxReturn($data);
    }


/*    public function getContent(){
        $goodsId = I('get.goods_id');
        $content = M('Goods')->where(array('goods_id'=>$goodsId))->getField('goods_content');
        $content = str_replace('src', 'class="lazy"  data-original', $content);

        $content = html_entity_decode($content);

        $this->ajaxReturn(array('content'=>$content));
    }*/



    //显示特殊商品领取页面
    public function  takeSpecGoods(){

        $id = I('id');
        if($id != '')
            $spec = M('SpecGoods')->where(array('id'=>$id))->find();

        $title = M('region')->where(array('id'=>$spec['region_id']))->getField('name');
        $title = str_replace('省', '', $title);
        self::jsSDK();//分享
//        $this->assign('title', $title . '特产试吃装');
        $this->assign('title', '新用户礼品');
        $this->assign('specGoods', $spec);
        $this->display('specGoods');
    }


    public function  onplace(){

//        $user = $this->getUser();
//        $json = get_ip_lookup();
        $c = session('city');
//        var_dump($json);

        $this->assign('json', $c);
        $this->assign('id', I('get.id'));
        $this->display();
    }


    public function ajaxTakeGoods(){
        $logic = new UserLogic();
        $takGoods = D('TakSpecGoods');
        $user = $this->getUser();
//        $user['user_id'] = 0;
        //判断该用户是否领取过该免费商品
        if(M('TakeSpecGoodsLog')->where(array('user_id'=>$user['user_id'], 'goods_id'=>I('post.goods_id')))->count())
            $this->ajaxReturn(array('status'=>-1, 'msg'=>'每个用户只能领取一次'));
  /*      C('TOKEN_ON',false);
        if(!$takGoods->create(I('post.'), 1))
        {
            $error = $takGoods->getError();
            $error_msg = array_values($error);
            $this->ajaxReturn(array('status'=>-1, 'msg'=>$error_msg[0]));
        }
        else
        {*/
            $addre = session('city');
//            $user_id = $user['user_id'];
//            $this->ajaxReturn(array('status'=>'-1', 'msg'=>$takGoods->mobile));
      /*      if(!check_mobile($takGoods->mobile)){

                $this->ajaxReturn(array('status'=>-1, 'msg'=>'手机号错误'));
            }*/
    /*        if(!$addre['location'] || !$addre)
            {
                $addre['location'] = '';
            }*/
            $goods_id = I('goods_id');


            $specGoods = M('SpecGoods')->where(array('id'=>$goods_id))->find();
            //获取当前省份配送员ID
            $send_user_id = M('users')->where(array('type'=>1, 'region_id'=>$specGoods['region_id']))->getField('user_id');
            if(!$send_user_id)
                $this->ajaxReturn(array('status'=>-1, 'msg'=>'领取失败', 's'=>$specGoods));


            $takGoods = array(
                'user_id'     => $user['user_id'],
                'address'     => $addre['location'],
                'region_id'   => $specGoods['region_id'],
                'goods_name'  => $specGoods['goods_name'],
                'image_1'     => $specGoods['image1'],
                'image_2'     => $specGoods['image2'],
                'send_user_id'=> $send_user_id,
                'status'      => 1,
                'create_time' => time()
            );

            M('TakSpecGoods')->add($takGoods);
          /*  $takGoods->user_id= $user['user_id'];
            $takGoods->address = $addre['location'];
            $takGoods->region_id = $specGoods['region_id'];
            $takGoods->goods_name = $specGoods['goods_name'];
            $takGoods->image_1 = $specGoods['image1'];
            $takGoods->image_2 = $specGoods['image2'];
            $takGoods->send_user_id = $send_user_id;
            $takGoods->status   = 1;
            $takGoods->create_time = time();
            $takGoods->add();*/
            $this->addTakSpecGoods($user['user_id'], $goods_id, 1);
            //返利给上级用户
            //获取免费领取返利
//            $rebateMoney = M('config')->where(array('id'=>74))->getField('value');
//            $logic->rebateLastUser((double)$rebateMoney, $user['user_id']);
            //添加到记录表中

            $this->ajaxReturn(array('status'=>1, 'msg'=>'领取成功'));
        }

//    }

    private function addTakSpecGoods($user_id, $goods_id, $type){
        $data = array('user_id'=>$user_id, 'goods_id'=>$goods_id, 'type'=>$type, 'add_time'=>time());
        M('TakeSpecGoodsLog')->add($data);
    }

    /**
     * ajax收藏商品
     */

    public function ajaxCollectGoods(){
        $goods_id = I('goods_id');
        $user = $this->getUser();
        $logic = new GoodsLogic();
        $result = $logic->collect_goods($user['user_id'],$goods_id);
        $this->ajaxReturn($result);
    }

    /**
     * ajax取消收藏
     */
    public function ajaxCancelCollect(){
        $collect_id = I('collect_id');
        $user = $this->getUser();
        $logic = new GoodsLogic();
        $result = $logic->cancelCollectGoods($user['user_id'],$collect_id);
        if($result){
            $this->ajaxReturn(array('success'=>true,'message'=>'取消收藏成功！'));
        }else{
            $this->ajaxReturn(array('success'=>false,'message'=>'取消收藏失败！'));
        }

    }

    /**
     * 跳转到我的收藏界面
     */
    public function collection(){
        $logic = new GoodsLogic();
        $user = $this->getUser();
        $goodsList = $logic->getCollectionGoodsList($user['user_id']);
        $this->assign('goodsList',$goodsList);
        $this->assign('count',count($goodsList));
        $this->display();
    }

    public function  kefu(){

        $this->display();

    }

}